package com.ytsky.hctechnologysys.controller;

import com.github.pagehelper.PageInfo;

import com.ytsky.hctechnologysys.entity.Job;
import com.ytsky.hctechnologysys.service.JobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dell
 */
@Controller
public class JobController {
    private  static final Logger logger = LoggerFactory.getLogger(JobController.class);


    @Autowired
    private JobService jobService;

    /**
     *返回招聘信息添加界面
     * @return
     */
    @GetMapping("/job/CandidateAdd")
    public ModelAndView CandidateAddView(){
        ModelAndView mav = new ModelAndView("job/CandidateAdd");
        return  mav;

    }

    /**
     *
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @GetMapping("/job/Candidate")
    public ModelAndView CandidateChangeView(
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "100") int pageSize,
            @RequestParam(name = "keyword",required = false) String keyword
    ){
        ModelAndView mav = new ModelAndView("job/Candidate");
        PageInfo<Job> page =  jobService.findByKeyword(pageNum,pageSize,keyword);
        mav.addObject("page",page);
        return mav;
    }


    @GetMapping("/job/CandidateModify")
    public  ModelAndView CandidateModifyView(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "100") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ){
        ModelAndView mav = new ModelAndView("job/CandidateModify");
        Job job = jobService.findById(id);
        mav.addObject("job",job);
        return mav;
    }


    @GetMapping("/job/CandidateRemove")
    public  ModelAndView CandidateRemove(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "100") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    )throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/job/Candidate?pageNum="+ pageNum  +
                "&pageSize=" + pageSize +
                "&keyword" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        boolean result = jobService.remove(id);
        return mav;
    }


    @PostMapping("/job/CandidateAdd")
    public ModelAndView CandidateAdd(@Validated Job job, BindingResult bindingResult){
        //redirect表示重定向响应
        //给浏览器发送一个请求地址，而没有任何视图内容或数据
        //浏览器会使用收到的地址，重新发送一个Get请求，由于是新请求，因此没有缓存上一次请求的数据，从而达到防止重复提交表单的目的
        ModelAndView mav = new ModelAndView("redirect:/job/CandidateAdd");

        Map<String,String> errorMessages = new HashMap<>();
        if (bindingResult.hasErrors()){
            //如果由验证错误消息，那么要进行处理
            //获得出现错误域，以及相应的错误消息文本
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            //错误信息放入到映射中
            for (FieldError error : fieldErrors){
                //从每一个域错误对象中取出域名称，错误消息，加到映射集合中
                errorMessages.put(error.getField(),error.getDefaultMessage());
            }
            //将错误信息发送给视图
            mav.addObject("errorMessages",errorMessages);
            //将客户填写的而信息，重新显示在表单中
            mav.addObject("job",job);
            //由于没有保存数据，因此不必进行重定向，内部转发请求到视图，同时还要保留请求数据，以及相应的信息
            mav.setViewName("/job/CandidateAdd");
        }else{
            //如果没有错误信息，验证通过
            //调用服务方法保存客户数据
            boolean result = jobService.append(job);
            if (result){
                logger.info("新增员工信息成功 - "+job);
            }else{
                logger.info("新增员工信息失败 - "+job);
            }
        }
        return  mav;
    }


    @PostMapping("/job/CandidateModify")
    public ModelAndView CandidateModify(
            Job job,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "100") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/job/Candidate?pageNum="+ pageNum  +
                "&pageSize=" + pageSize +
                "&keyword" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        boolean result = jobService.modify(job);
        System.out.println(result);
        return mav;

    }

    /**
     * 返回录用信息修改页面
     * @return
     */
    @GetMapping("/job/CandidateAuthorityManager")
    public ModelAndView CandidateAuthorityManagerView(){
        ModelAndView mav = new ModelAndView("job/CandidateAuthorityManager");
        return mav;
    }
}
